""" System imports """
import os,sys
import logging

""" Other modules """
import pygame

""" Game """
from constants import *

""" Set up logging """
_log = logging.getLogger("epicquest.resourcemanager")
_log.debug("Initializing Resource Manager")

class ResourceManager():
    
    __instance = None
    
    class __impl:
        """ Actual implementation of the ResourceManager interface """

        DEFAULT_IMAGE = None
        DEFAULT_IMAGE_PATH = "resources/sprites/notfound.jpg"
        
        images = {}
        sounds = {}
        
        def __init__(self):
            try:
                self.DEFAULT_IMAGE = pygame.image.load(self.DEFAULT_IMAGE_PATH)
            except:
                self.DEFAULT_IMAGE = pygame.surface.Surface((32,32))
                
        
        def load_image(self, file, spritex = 0, spritey = 0, convert = True, alpha_color = (84,138,150)):
            """ Loads an image, or the 'not found' image if there is an error 
            
            First checks if the image has already been loaded
            If so, it returns a copy of the surface, after adjusting the size and converting if necessary
            If not, it loads the image, stores the surface for later, then returns the surface 
            """
            
            if file == 0:
                return self.DEFAULT_IMAGE
            
            if file not in self.images:
                try:
                    self.images[file] = pygame.image.load(file)
                except:
                    self.images[file] = self.DEFAULT_IMAGE
            
            #image = self.images[file].copy()
            image = self.images[file].subsurface((spritex, spritey, 32, 32))
            image.set_colorkey(alpha_color)
            image.convert()
            #image = pygame.transform.smoothscale(image, size)
            return image
            
        def play_sound(self, sound = None):
            if sound is None:
                return
            
            if sound not in self.sounds:
                try:
                    self.sounds[sound] = pygame.mixer.Sound(sound)
                except:
                    self.sounds[sound] = None
            
            if self.sounds[sound] is None:
                return
            
            self.sounds[sound].play()
                
                
    def __init__(self):
        if ResourceManager.__instance is None:
            # Create and remember instance
            ResourceManager.__instance = ResourceManager.__impl()
            
        self.__dict__['_ResourceManager__instance'] = ResourceManager.__instance

    def __getattr__(self, attr):
        """ Delegate access to implementation """
        return getattr(self.__instance, attr)

    def __setattr__(self, attr, value):
        """ Delegate access to implementation """
        return setattr(self.__instance, attr, value)
       